package com.example.provider.config.interceptor;

import com.example.provider.config.util.HttpContextHeaderHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@Component
public class HeaderInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(HeaderInterceptor.class);

    // 在请求处理之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        Map<String, Object> headers = new HashMap<>();
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            logger.info("Header Name: " + headerName + " - Header Value: " + request.getHeader(headerName));
            headers.put(headerName, request.getHeader(headerName));
        }

        HttpContextHeaderHolder.set(headers);
        return true;  // 返回 true，继续请求处理链
    }

    // 在请求处理完成之后
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HttpContextHeaderHolder.clear();
    }
}